package app1.rapidsquare.com.database;

import java.util.ArrayList;

import org.apache.http.entity.StringEntity;
import org.json.JSONObject;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

import app1.rapidsquare.com.Utility.Utility;
import app1.rapidsquare.com.classes.User;

public class AgileUserProvider extends AgileSyncHelper<User> implements
        IAgileProvider<User> {

    // TABLE

    public static final String TABLE_NAME = "Users";

    // COLUMNS

    public static final String ID = "Id";
    public static final String EMAIL = "Email";
    public static final String PASSWORD = "Password";
    public static final String FIRST_NAME = "FirstName";
    public static final String LAST_NAME = "LastName";
    public static final String PHONE = "Phone";
    public static final String TITLE = "Title";
    public static final String COMPANY = "Company";
    public static final String SITE = "Site";
    public static final String INFO = "Info";
    public static final String CODE = "Code";
    public static final String ADDITIONAL_INFO = "AdditionalInfo";
    public static final String MODIFIED_DATE = "ModifiedDate";
    public static final String CITY = "City";
    public static final String STATE = "State";
    public static final String FACEBOOK_ID = "FacebookId";
    public static final String GOOGLE_PLUS_ID = "GooglePlusId";
    public static final String LINKED_IN_ID = "LinkedInId";
    public static final String IS_DELETE = "IsDelete";
    public static final String FACEBOOK_NAME = "FacebookName";
    public static final String GOOGLE_PLUS_NAME = "GooglePlusName";
    public static final String LINKED_IN_NAME = "LinkedInName";

    public AgileUserProvider(Context context) {
        super(context, User.class);
    }

    @Override
    public synchronized User SelectById(int id) {

        User user = null;
        try {
            SQLiteDatabase sqliteDataBase = getSqliteHelper().getReadableDatabase();
            if (sqliteDataBase.isOpen() && id > 0) {

                String mQuery = " SELECT * FROM [" + TABLE_NAME
                        + "] WHERE IsDelete = 0 and Id=" + id;


                Cursor mCursor = sqliteDataBase.rawQuery(mQuery, null);

                if (mCursor.getCount() < 1) {
                    if (!mCursor.isClosed())
                        mCursor.close();

                    sqliteDataBase.close();
                    Close();
                    return user;
                }

                mCursor.moveToFirst();

                do {
                    user = new User();
                    user.Id = mCursor.getInt(mCursor.getColumnIndex(ID));
                    user.FirstName = mCursor.getString(mCursor
                            .getColumnIndex(AgileUserProvider.FIRST_NAME));
                    user.Email = mCursor.getString(mCursor
                            .getColumnIndex(AgileUserProvider.EMAIL));
                    user.Password = mCursor.getString(mCursor
                            .getColumnIndex(AgileUserProvider.PASSWORD));
                    user.LastName = mCursor.getString(mCursor
                            .getColumnIndex(AgileUserProvider.LAST_NAME));
                    user.Phone = mCursor.getString(mCursor
                            .getColumnIndex(AgileUserProvider.PHONE));
                    user.Title = mCursor.getString(mCursor
                            .getColumnIndex(AgileUserProvider.TITLE));
                    user.Company = mCursor.getString(mCursor
                            .getColumnIndex(AgileUserProvider.COMPANY));
                    user.Site = mCursor.getString(mCursor
                            .getColumnIndex(AgileUserProvider.SITE));
                    user.Info = mCursor.getString(mCursor
                            .getColumnIndex(AgileUserProvider.INFO));
                    user.Code = mCursor.getString(mCursor
                            .getColumnIndex(AgileUserProvider.CODE));
                    user.AdditionalInfo = mCursor.getString(mCursor
                            .getColumnIndex(AgileUserProvider.ADDITIONAL_INFO));
                    user.City = mCursor.getString(mCursor
                            .getColumnIndex(AgileUserProvider.CITY));
                    user.State = mCursor.getString(mCursor
                            .getColumnIndex(AgileUserProvider.STATE));

                    user.FacebookId = mCursor.getString(mCursor
                            .getColumnIndex(AgileUserProvider.FACEBOOK_ID));
                    user.GooglePlusId = mCursor.getString(mCursor
                            .getColumnIndex(AgileUserProvider.GOOGLE_PLUS_ID));
                    user.LinkedInId = mCursor.getString(mCursor
                            .getColumnIndex(AgileUserProvider.LINKED_IN_ID));
                    user.FacebookName = mCursor.getString(mCursor
                            .getColumnIndex(AgileUserProvider.FACEBOOK_NAME));
                    user.GooglePlusName = mCursor.getString(mCursor
                            .getColumnIndex(AgileUserProvider.GOOGLE_PLUS_NAME));
                    user.LinkedInName = mCursor.getString(mCursor
                            .getColumnIndex(AgileUserProvider.LINKED_IN_NAME));
                    break;

                } while (mCursor.moveToNext());

                if (!mCursor.isClosed())
                    mCursor.close();

                sqliteDataBase.close();
            }

            Close();
        } catch (Exception ex) {
            Utility.Log("AgileUserProvider -> SelectById ", ex);
        }
        return user;
    }

    @Override
    public synchronized void Update() {
        if (!Utility.isNullOrEmpty(getUserToken())) {

            try {

                SQLiteDatabase sqliteDataBase = getSqliteHelper().getReadableDatabase();

                if (sqliteDataBase.isOpen()) {

                    String lastModifiedDate = "2012-10-08 06:43:05";

                    Cursor c = sqliteDataBase.query(TABLE_NAME, new String[]{
                                    ID, MODIFIED_DATE}, null, null, null, null,
                            MODIFIED_DATE + " desc");

                    if (c.getCount() > 0) {
                        c.moveToFirst();

                        lastModifiedDate = c.getString(
                                c.getColumnIndex(MODIFIED_DATE)).trim();
                    }
                    if (!c.isClosed())
                        c.close();

                    sqliteDataBase.close();

                    setURL(Utility.USERS_SYNC_URL);

                    JSONObject postObject = new JSONObject();
                    postObject.accumulate("UserToken", getUserToken());
                    postObject.accumulate("ModifiedDate", lastModifiedDate);

                    this.httpEntity = new StringEntity(postObject.toString());

                    RunSync();
                }

                Close();

            } catch (Exception e) {
                Utility.Log("AgileUsersProviser - > Update ", e);
            }
        }
    }

    @Override
    public synchronized void Close() {
        if (getSqliteHelper() != null)
            getSqliteHelper().close();
    }

    @Override
    public synchronized void Delete() {

        try {
            SQLiteDatabase sqliteDataBase = getSqliteHelper().getWritableDatabase();
            if (sqliteDataBase.isOpen()) {
                sqliteDataBase.delete(TABLE_NAME, "IsDelete=1", null);
                sqliteDataBase.close();
            }

            Close();
        } catch (Exception e) {
            Utility.Log("AgileUsersProviser - > DELETE ", e);
        }
    }

    @Override
    public synchronized void UpdateData(ArrayList<User> usersList) {

        try {
            SQLiteDatabase sqliteDataBase = getSqliteHelper().getWritableDatabase();

            if (sqliteDataBase.isOpen()) {

                for (User user : usersList) {

                    ContentValues values = new ContentValues();
                    values.put(ID, user.Id);
                    values.put(EMAIL, user.Email);
                    values.put(PASSWORD, user.Password);
                    values.put(FIRST_NAME, user.FirstName);
                    values.put(LAST_NAME, user.LastName);
                    values.put(PHONE, user.Phone);
                    values.put(TITLE, user.Title);
                    values.put(COMPANY, user.Company);
                    values.put(SITE, user.Site);
                    values.put(INFO, user.Info);
                    values.put(CODE, user.Code);
                    values.put(ADDITIONAL_INFO, user.AdditionalInfo);
                    values.put(MODIFIED_DATE, Utility.getUTCDateFormat().format(user.ModifiedDate));
                    values.put(CITY, user.City);
                    values.put(STATE, user.State);
                    values.put(FACEBOOK_ID, user.FacebookId);
                    values.put(GOOGLE_PLUS_ID, user.GooglePlusId);
                    values.put(LINKED_IN_ID, user.LinkedInId);
                    values.put(FACEBOOK_NAME, user.FacebookName);
                    values.put(GOOGLE_PLUS_NAME, user.GooglePlusName);
                    values.put(LINKED_IN_NAME, user.LinkedInName);
                    values.put(IS_DELETE, user.IsDelete ? 1 : 0);

                    long rowId = -1;

                    Cursor c = sqliteDataBase.query(TABLE_NAME, null, ID + "='"
                            + user.Id + "'", null, null, null, null);

                    if (c.getCount() > 0) {

                        rowId = sqliteDataBase.updateWithOnConflict(TABLE_NAME,
                                values, ID + "='" + user.Id + "'", null, 5);

                    } else {

                        rowId = sqliteDataBase.insertWithOnConflict(TABLE_NAME,
                                null, values, 5);
                    }

                    if (!c.isClosed())
                        c.close();

                    if (rowId < 0) {
                        Utility.Log("AgileUsersProviser - > is not inserted or updated ", new Exception());
                    }
                }

                sqliteDataBase.close();
            }

            Close();

        } catch (Exception e) {
            Utility.Log("AgileUsersProviser - > UpdateData", e);
        }
    }
}
